# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name:         sfp_malwarepatrol
# Purpose:      SpiderFoot plug-in to search MalwarePatrol's daatabase for
#               potential malicious IPs/hostnames.
#
# Author:      Steve Micallef <steve@binarypool.com>
#
# Created:     25/07/2016
# Copyright:   (c) Steve Micallef 2016
# Licence:     GPL
# -------------------------------------------------------------------------------

from spiderfoot import SpiderFootEvent, SpiderFootPlugin


class sfp_malwarepatrol(SpiderFootPlugin):

    meta = {
        'name': "MalwarePatrol",
        'summary': "Searches malwarepatrol.net's database of malicious URLs/IPs.",
        'flags': ["apikey"],
        'useCases': ["Investigate", "Passive"],
        'categories': ["Reputation Systems"],
        'dataSource': {
            'website': "https://www.malwarepatrol.net/",
            'model': "FREE_AUTH_LIMITED",
            'references': [
                "https://www.malwarepatrol.net/tech-support/",
                "https://www.malwarepatrol.net/integrations-formats-tip-siem-soar/",
                "https://www.malwarepatrol.net/community-contribution-suspicious-emails/",
                "https://www.malwarepatrol.net/non-commercial/#lists"
            ],
            'apiKeyInstructions': [
                "Visit https://www.malwarepatrol.net/free-guard-block-list/",
                "Register a free account",
                "The Password/Receipt number will be mailed to your email"
            ],
            'favIcon': "https://www.malwarepatrol.net/wp-content/uploads/2020/02/rsz_12logo-150x150.png",
            'logo': "https://www.malwarepatrol.net/wp-content/uploads/2016/06/rsz_mp_logo_clear_-_small.png",
            'description': "Based in the USA and Brazil, our history is one of community spirit and dedication to "
            "Internet security that began in 2005 when a group started sharing malicious links using a simple mailing list.\n"
            "Collecting, analyzing, and sharing data for over a decade has allowed us "
            "to develop an extensive network of sensors, sharing agreements, and community contributors. "
            "The result is our vast database of unique and historically rich – “intelligent” – threat data.",
        }
    }

    # Default options
    opts = {
        "api_key": ""
    }
    optdescs = {
        "api_key": "Malwarepatrol.com 'receipt' ID, provided once signing up for their open-source feed. Without this you cannot obtain their feed."
    }
    results = None
    errorState = False

    def setup(self, sfc, userOpts=dict()):
        self.sf = sfc
        self.results = self.tempStorage()

        for opt in list(userOpts.keys()):
            self.opts[opt] = userOpts[opt]

    # What events is this module interested in for input
    def watchedEvents(self):
        return ["INTERNET_NAME", "IP_ADDRESS",
                "AFFILIATE_INTERNET_NAME", "AFFILIATE_IPADDR",
                "CO_HOSTED_SITE"]

    # What events this module produces
    # This is to support the end user in selecting modules based on events
    # produced.
    def producedEvents(self):
        return ["MALICIOUS_IPADDR", "MALICIOUS_INTERNET_NAME",
                "MALICIOUS_AFFILIATE_IPADDR", "MALICIOUS_AFFILIATE_INTERNET_NAME",
                "MALICIOUS_COHOST"]

    def queryAddr(self, qaddr):
        data = dict()
        url = "http://lists.malwarepatrol.net/cgi/getfile?receipt=" + \
              self.opts['api_key'] + "&product=8&list=smoothwall"

        data['content'] = self.sf.cacheGet("sfmalwarepatrol", 72)
        if data['content'] is None:
            data = self.sf.fetchUrl(url, useragent=self.opts['_useragent'])
            if data['content'] is None:
                self.sf.error("Unable to fetch " + url)
                return None
            else:
                self.sf.cachePut("sfmalwarepatrol", data['content'])

        for line in data['content'].split('\n'):
            if len(line) < 2 or line.startswith('#'):
                continue

            if line.startswith(qaddr):
                return True

        return False

    # Handle events sent to this module
    def handleEvent(self, event):
        eventName = event.eventType
        srcModuleName = event.module
        eventData = event.data

        if self.errorState:
            return None

        self.sf.debug(f"Received event, {eventName}, from {srcModuleName}")

        if not self.opts['api_key']:
            self.sf.error("You enabled sfp_malwarepatrol but did not provide an receipt ID!")
            self.errorState = True
            return None

        if eventData in self.results:
            self.sf.debug("Skipping " + eventData + " as already searched.")
            return None

        self.results[eventData] = True

        evtType = ""
        if eventName in ['IP_ADDRESS', 'AFFILIATE_IPADDR']:
            if eventName == 'IP_ADDRESS':
                evtType = 'MALICIOUS_IPADDR'
            else:
                evtType = 'MALICIOUS_AFFILIATE_IPADDR'

        if eventName in ['INTERNET_NAME', 'CO_HOSTED_SITE',
                         'AFFILIATE_INTERNET_NAME']:
            if eventName == "INTERNET_NAME":
                evtType = "MALICIOUS_INTERNET_NAME"
            if eventName == 'AFFILIATE_INTERNET_NAME':
                evtType = 'MALICIOUS_AFFILIATE_INTERNET_NAME'
            if eventName == 'CO_HOSTED_SITE':
                evtType = 'MALICIOUS_COHOST'

        if self.queryAddr(eventData):
            evt = SpiderFootEvent(evtType, "MalwarePatrol [" + eventData + "]", self.__name__, event)
            self.notifyListeners(evt)

# End of sfp_malwarepatrol class
